﻿using System;
using System.Drawing;
using System.IO;
using System.Web.Security;

namespace AllNations
{
    public partial class UserProfile : MakeItWeb.Framework.MakeItWebAuthenticatedUserPage
    {
        private int _IconImageSize = 250;

        protected void Page_Load(object sender, EventArgs e)
        {
            btSaveProfile.Click += new EventHandler(btSaveProfile_Click);
            lblSuccess.Text = string.Empty;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (ANMCPageViews.SelectedIndex == viewMyProfile.Index)
            {
                lblUserName.Text = CurrentMember.UsernameTxt;
                txtKoreanNm.Text = CurrentMember.KoreanNm;
                txtFirstnameTxt.Text = CurrentMember.FirstnameTxt;
                txtLastnameTxt.Text = CurrentMember.LastnameTxt;
                txtEmailaddr.Text = CurrentMember.EmailaddrTxt;
                lblConfirmationMessage.Visible = CurrentMember.ConfirmationGuid != Guid.Empty;
                txtHomeAddressTxt.Text = CurrentMember.HomeAddressTxt;
                txtHomeAddress2Txt.Text = CurrentMember.HomeAddress2Txt;
                txtHomeCityTxt.Text = CurrentMember.HomeCityTxt;
                txtHomeStateCd.Text = CurrentMember.HomeStateCd;
                txtHomeZipCd.Text = CurrentMember.HomeZipCd;
                txtHomePhonenumTxt.Text = CurrentMember.HomePhonenumTxt;
                txtCellPhonenumTxt.Text = CurrentMember.CellPhonenumTxt;
                rdpBirthDate.SelectedDate = CurrentMember.Birthdate;
                imgProfileIcon.Visible = !string.IsNullOrEmpty(CurrentMember.IconFilenameTxt);
                if (!string.IsNullOrEmpty(CurrentMember.IconFilenameTxt))
                    imgProfileIcon.ImageUrl = string.Format("{0}?t={1}", CurrentMember.IconFilenameTxt, DateTime.Now.Ticks);
                lblIconSizeRule.Text = string.Format("(If image is bigger than {0} pixels in width or height, it will be cropped to {0}pixels.)", _IconImageSize);
            }
        }

        void btSaveProfile_Click(object sender, EventArgs e)
        {
            try
            {
                CurrentMember.FirstnameTxt = txtFirstnameTxt.Text.Trim();
                CurrentMember.LastnameTxt = txtLastnameTxt.Text.Trim();
                CurrentMember.KoreanNm = txtKoreanNm.Text.Trim();
                CurrentMember.EmailaddrTxt = txtEmailaddr.Text.Trim();
                CurrentMember.HomeAddressTxt = txtHomeAddressTxt.Text.Trim();
                CurrentMember.HomeAddress2Txt = txtHomeAddress2Txt.Text.Trim();
                CurrentMember.HomeCityTxt = txtHomeCityTxt.Text.Trim();
                CurrentMember.HomeStateCd = txtHomeStateCd.Text.Trim();
                CurrentMember.HomeZipCd = txtHomeZipCd.Text.Trim();
                CurrentMember.HomePhonenumTxt = txtHomePhonenumTxt.Text.Trim();
                CurrentMember.CellPhonenumTxt = txtCellPhonenumTxt.Text.Trim();
                if (fuProfileIcon.UploadedFiles.Count > 0)
                {
                    string sFilename = string.Format("~/Images/Icons/{0}{1}", CurrentMember.UserId, fuProfileIcon.UploadedFiles[0].GetExtension());
                    SaveProfileImage(fuProfileIcon.UploadedFiles[0], sFilename);
                    CurrentMember.IconFilenameTxt = sFilename;
                    imgProfileIcon.ImageUrl = string.Format("{0}?t={1}", CurrentMember.IconFilenameTxt, DateTime.Now.Ticks);
                }
                CurrentMember.Birthdate = rdpBirthDate.SelectedDate;
                CurrentMember.Save();

                lblSuccess.Text = "프로파일이 저장 되었습니다.";
            }
            catch (Exception ex)
            {
                lblSuccess.Text = string.Format("저장 하는데 문제가 있습니다: {0}", ex.Message);
            }
        }

        private void SaveProfileImage(Telerik.Web.UI.UploadedFile uploadedFile, string sFilename)
        {
            Image oImg = ResizeImage(uploadedFile.InputStream, _IconImageSize);
            if (_IconImageSize > Math.Min(oImg.Width, oImg.Height))
                _IconImageSize = Math.Min(oImg.Width, oImg.Height);

            Bitmap oTarget = new Bitmap(_IconImageSize, _IconImageSize);
            Graphics oThumbnail = Graphics.FromImage(oTarget);
            oThumbnail.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            oThumbnail.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            oThumbnail.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            oThumbnail.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            int X = 0;
            int Y = 0;
            oThumbnail.DrawImage(oImg, new Rectangle(0, 0, _IconImageSize, _IconImageSize), X, Y, _IconImageSize, _IconImageSize, GraphicsUnit.Pixel);


            oTarget.Save(Server.MapPath(sFilename), System.Drawing.Imaging.ImageFormat.Png);

            // clean up
            oImg.Dispose();
            oTarget.Dispose();
            oThumbnail.Dispose();

            // clean up the image file handle
            oImg.Dispose();
            //uploadedFile.SaveAs(Server.MapPath(sFilename));
        }

        private Image ResizeImage(Stream s, int _IconImageSize)
        {
            int iWidth = 0;
            int iHeight = 0;

            Image oImg = System.Drawing.Image.FromStream(s);
            if (_IconImageSize > Math.Max(oImg.Width, oImg.Height))
                _IconImageSize = Math.Max(oImg.Width, oImg.Height);

            if (oImg.Width > oImg.Height)
            {
                iWidth = _IconImageSize;
                iHeight = (iWidth * oImg.Height) / oImg.Width;
            }
            else
            {
                iHeight = _IconImageSize;
                iWidth = (iHeight * oImg.Width) / oImg.Height;
            }

            Image img;
            Bitmap oTarget = new Bitmap(iWidth, iHeight);
            Graphics oThumbnail = Graphics.FromImage(oTarget);
            oThumbnail.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            oThumbnail.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            oThumbnail.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            oThumbnail.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            oThumbnail.DrawImage(oImg, new Rectangle(0, 0, iWidth, iHeight));
            using (MemoryStream ms = new MemoryStream())
            {
                oTarget.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                img = Image.FromStream(ms);
            }
            // clean up
            oImg.Dispose();
            oTarget.Dispose();
            oThumbnail.Dispose();

            // clean up the image file handle
            oImg.Dispose();

            return img;
        }
    }
}